﻿<%@ WebHandler Language="C#" Class="ContainerStepInfoWorkReportPageHandler" %>

using System;
using System.Web;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Linq;
using BusinessRule.Business;
using System.Data;
using Newtonsoft.Json;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
using System.Collections;
using BusinessRule.DTO;
using System.Web.SessionState;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using Camstar.WebClient.WebServicesProxy.InSiteWebServices;

//Description: 工步报工页面处理程序
//Copyright (c) : 通力凯顿（北京）系统集成有限公司
//Writer:zhangrj
//create Date:2022-07-29
public class ContainerStepInfoWorkReportPageHandler : IHttpHandler, IRequiresSessionState
{
    CurrentUserInfo m_UserInfo;
    uLMSCommonBusiness m_Common = new uLMSCommonBusiness();
    YPContainerBusiness ypBusiness = new YPContainerBusiness();
    RbContainerBusiness rbBusiness = new RbContainerBusiness();
    uLMSIssueIBusiness m_issueData = uMESBusinessFactory.instance.GetuLMSIssueObject();
    uLMSWorkReportIBusiness reportBusiness = uMESBusinessFactory.instance.GetuLMSWorkReportObject();
    uLMSDispatchIBusiness m_DispatchObj = uMESBusinessFactory.instance.GetuLMSDispatchObject();
    uLMSContainerIBusiness m_ContainerObj = uMESBusinessFactory.instance.GetuLMSContainerObject();
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            string action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            if (m_UserInfo == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "数据过期，请重新登录" }));
                return;
            }
            switch (action)
            {
                case "InitData"://初始化工步报工页面
                    InitData(context);
                    break;
                case "GetStepInfoList"://获取工步报工列表（未启用）
                    GetStepInfoList(context);
                    break;
                case "GetRBStepInfoList"://获取工步报工列表（热表）
                    GetRBStepInfoList(context);
                    break;
                case "GetSurPlusEmployeeInfo"://获取结余件人
                    GetSurPlusEmployeeInfo(context);
                    break;
                case "GetFillData"://获取填充数据
                    GetFillData(context);
                    break;
                case "SetInputCheckPoint"://设置实测值Session
                    SetInputCheckPoint(context);
                    break;
                case "SaveStepInfoWorkReportData"://保存工步报工数据
                    SaveStepInfoWorkReportData(context);
                    break;
                //批量报工
                case "GetStepInfoBatchList"://获取批量报工数据
                    GetStepInfoBatchList(context);
                    break;
                case "SaveStepInfoBatchWorkReportData"://保存批量报工数据
                    SaveStepInfoBatchWorkReportData(context);
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            var result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }

    /// <summary>
    /// 获取批量报工数据
    /// </summary>
    /// <param name="context"></param>
    public void GetStepInfoBatchList(HttpContext context)
    {
        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("FactoryID", m_UserInfo.FactoryID);
        para.Add("WorkerID", m_UserInfo.EmployeeID.ToString());
        para.Add("CurrentPageIndex", context.Request["pageIndex"].ToString());
        para.Add("PageSize", context.Request["pageSize"].ToString());
        para.Add("OrderName", context.Request["orderName"].ToString());
        para.Add("ProductName", context.Request["productName"].ToString());
        para.Add("ContainerName", context.Request["containerName"].ToString());
        para.Add("CombinateName", context.Request["combinateName"].ToString());
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        if (context.Request["opType"].ToString() == "1")
        {
            result = reportBusiness.GetApsStepInfoBatchReportList(para);
        }
        else
        {
            result = reportBusiness.GetStepInfoBatchReportList(para);
        }
        //加入判断是否有录入检测项
        result.DBTable.Columns.Add("IsFillCheckPoint");
        string msg = string.Empty;
        foreach (DataRow item in result.DBTable.Rows)
        {
            msg = "";
            m_ContainerObj.IsValidRBCheckPointByStepinfo(item, 0, ref msg);
            item["IsFillCheckPoint"] = msg;
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 保存批量报工数据
    /// </summary>
    /// <param name="context"></param>
    public void SaveStepInfoBatchWorkReportData(HttpContext context)
    {
        DataTable paramDt = JsonConvert.DeserializeObject<DataTable>(context.Request["paramDt"].ToString());
        if (!paramDt.Columns.Contains("NOTES"))
        {
            paramDt.Columns.Add("NOTES");
        }
        List<object[]> SQLStringList = new List<object[]>();
        string ContainerStepDispatchInfoIDs = "";

        uMESProcessResult result = IsVaildBatchReport(paramDt);
        if (result.Result)
        {
            DataTable dt = result.DBTable;
            foreach (DataRow item in dt.Rows)
            {
                //if (!containerIDs_str.Contains(item["ContainerID"].ToString()))
                //{
                //    containerIDs_str += "'" + item["ContainerID"].ToString() + "',";
                //}
                ContainerStepDispatchInfoIDs += " OR csd.containerstepdispatchid='" + item["ContainerStepDispatchID"].ToString() + "'";
                ContainerStepWorkReportDTO dto = new ContainerStepWorkReportDTO();
                dto.WorkerID = m_UserInfo.EmployeeID.ToString();
                dto.FactoryID = m_UserInfo.FactoryID;
                dto.WorkCenterID = m_UserInfo.WorkCenterID;
                dto.TeamID = m_UserInfo.TeamID;
                dto.FirstContainerNo = ""; //首件批次号
                dto.KeyProcessBatchNo = ""; //关键过程批次号
                dto.Note = item["NOTES"].ToString(); //备注 
                dto.ContainerID = item["ContainerID"].ToString();
                dto.WorkflowstepID = item["WorkflowStepID"].ToString();
                dto.StepInfoID = item["StepInfoID"].ToString();
                dto.ResourceID = "";//设备
                dto.CheckerID = "";//检验员
                dto.SelfCheckOutofToleranceQty = 0;
                dto.SelfCheckLossQty = 0;
                int wipqty = int.Parse(item["WipQty"].ToString());
                int disqty = int.Parse(item["DisQty"].ToString());
                dto.Qty = disqty <= wipqty ? disqty : wipqty;//报工数
                dto.SeleCheckQualifiedQty = dto.Qty;//自检合格数
                dto.CheckType = 2;//默认序检
                dto.ContainerStepDispatchID = item["ContainerStepDispatchID"].ToString();
                dto.ContainerStepWorkReportID = Guid.NewGuid().ToString();
                SQLStringList.Add(reportBusiness.FillContainerStepInfoWorkReportDataTrans(dto, ""));//插入报工数据
                Dictionary<string, string> para = new Dictionary<string, string>();
                para.Add("type", "2");
                para.Add("WorkerID", dto.WorkerID);
                para.Add("ContainerStepDispatchID", item["ContainerStepDispatchID"].ToString());
                SQLStringList.Add(reportBusiness.FillReceviceDispatch2(para));//更新派工表接收数据
                SQLStringList.Add(reportBusiness.UpdateStepInfoCheckPointReport(dto));//更新可能的检测项
                if (item["ContainerType"].ToString() == "3") //如果是批量带子序号，则要添加子序号报工
                {
                    DataTable dtChild = m_Common.GetContainerInfoByPerContianerID2(item["ContainerID"].ToString());
                    foreach (DataRow drChild in dtChild.Rows)
                    {
                        ContainerStepWorkReportChildDTO entity = new ContainerStepWorkReportChildDTO();
                        entity.ChildContainerID = drChild["ContainerID"].ToString();//子序号批次ID
                        entity.SelfCheckLossQty = "0";//自检报废
                        entity.ContainerStepWorkReportID = dto.ContainerStepWorkReportID;//父报工ID
                        SQLStringList.Add(reportBusiness.FillContainerStepInfoWorkReportChild2(entity));
                    }
                }
            }
            //containerIDs_str = containerIDs_str.Trim(',');
            //containerIDs_str = containerIDs_str.Trim('\'');
            //SQLStringList.Add(reportBusiness.FillUpdateStepCheckNum(containerIDs_str, 2));//更新批次检验类型
            ContainerStepDispatchInfoIDs = ContainerStepDispatchInfoIDs.Substring(3);
            //查询派工报工数据
            DataTable dtDis = GetWorkReportTimeReallyDisReportNum(ContainerStepDispatchInfoIDs);
            if (dtDis.Rows.Count == 0 || dtDis.Rows.Count != dt.Rows.Count)
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "未在页面记录找到报工对应的派工记录" }));
                return;
            }
            if (!reportBusiness.IsVaildDispatchForStepInfoWorkReport(ContainerStepDispatchInfoIDs))
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "派工记录已撤销，请刷新页面" }));
                return;
            }
            DataRow[] drs = dtDis.Select("reportqty>0");//查询是否有派工已报工
            if (drs.Length > 0)
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "存在已报工的派工，请重新查询" }));
                return;
            }
            if (SQLStringList.Count > 0)
            {
                if (!DatabaseAccess.DBUtility.DatabaseHelper.ExecuteSqlTran(SQLStringList))
                {
                    context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "报工异常" }));
                    return;
                }
            }
            m_DispatchObj.UpdateDispatchIsCompleteStatus(ContainerStepDispatchInfoIDs.Replace("csd", "csw")); //更新派工记录是否完工状态
            DataTable dt1 = dt.DefaultView.ToTable(true, new string[4] { "ContainerID", "WorkflowStepID", "WipQty", "StepInfoRev" });
            FillStepWorkReportInfo(dt1);//更新工序到报工表
            result.Message = "报工成功";
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 验证批量报工
    /// </summary>
    /// <param name="dt"></param>
    /// <returns></returns>
    private uMESProcessResult IsVaildBatchReport(DataTable dt)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        int combinateCount = dt.AsEnumerable().Where(p => string.IsNullOrWhiteSpace(p["containerstepdispatchid"].ToString())).Count();//合卡批次的数量
        int commCount = dt.AsEnumerable().Where(p => !string.IsNullOrWhiteSpace(p["containerstepdispatchid"].ToString())).Count();//正常批次的数量
        if (combinateCount > 0 && commCount > 0)
        {
            result.Result = false;
            result.Message = "同时选择了合卡批次和正常批次，请重新选择";
            return result;
        }
        if (combinateCount > 0)
        {
            dt = GetCombinateContainerDetail(dt);
        }
        string msg = string.Empty;
        foreach (DataRow item in dt.Rows)
        {
            msg = "";
            if (!m_ContainerObj.IsValidRBCheckPointByStepinfo(item, 0, ref msg))
            {
                result.Result = false;
                result.Message = "存在未录入检测项的报工";
                break;
            }
            if (m_Common.JudeContainerHold(item["ContainerId"].ToString(), ref msg))
            {
                result.Message = "该批次已暂停，暂停原因：" + msg;
                result.Result = false;
                break;
            }
            if (IsOtherCheckPointed(item["ContainerID"].ToString(), item["StepInfoID"].ToString(), item["WorkflowStepID"].ToString()))
            {
                result.Result = false;
                result.Message = "工步【" + item["StepInfoName"].ToString() + "】存在其他工人录入检测项但未报工，请等待别人报工完成，或删除别人录入但未报工的检测项";
                break;
            }
            //验证特殊过程工序
            if (rbBusiness.IsErrorSpecialCourseSpecReport(item["ContainerID"].ToString(), item["ContainerStepDispatchID"].ToString(), m_UserInfo.EmployeeName, ref msg))
            {
                result.Result = false;
                result.Message = msg;
                break;
            }
            if (!dt.Columns.Contains("isCombinateVaild") && m_ContainerObj.IsCombinateContainer(item["ContainerID"].ToString()))//批次提交报工时，但已经合卡了
            {
                result.Result = false;
                result.Message = string.Format("批次：{0}已合卡，请重新查询", item["ContainerName"].ToString());
                break;
            }
        }
        result.DBTable = dt;
        return result;
    }
    /// <summary>
    /// 获取合卡批次的明细批次
    /// </summary>
    /// <param name="dt"></param>
    /// <returns></returns>
    private DataTable GetCombinateContainerDetail(DataTable dt)
    {
        string sql = @"SELECT csd.containerstepdispatchid, c.containername,c.containerid,ws.workflowstepname,csd.workflowstepid,c.workflowid,c.productid,
s1.stepinfoid,s1.stepno,s1.description stepinfoname,csd.createdate,c.qty wipqty,csd.qty disqty,c.containertype,
DECODE(c.CONTAINERTYPE,2,'批量加工',3,'批量带子序号', 7,'单件加工') AS CONTAINERTYPENAME,'{4}' NOTES,s1.revision stepinforev, '1' isCombinateVaild
FROM containercombinate cb 
LEFT JOIN containercurrentinfo c ON c.containerid = cb.containerid
LEFT JOIN containerstepdispatch2 csd ON csd.containerid = cb.containerid
LEFT JOIN Workflowstep ws ON ws.workflowstepid = csd.workflowstepid
LEFT JOIN stepinfo s1 ON s1.stepinfoid = csd.stepinfoid
LEFT JOIN containerstepdispatchdetail2 csdd ON csdd.containerstepdispatchid = csd.containerstepdispatchid
WHERE csd.isuse = 0 AND c.containerstatus = 1 AND c.isinstore =0 AND c.factoryid = '{1}' AND c.qty > 0
AND ((csd.WORKERID IS NOT NULL AND csd.WORKERID = '{0}') OR (csd.WORKERID IS NULL AND csdd.WORKERID='{0}'))   
AND NOT EXISTS(SELECT 1 FROM containerstepworkreport2 csw WHERE csw.containerstepdispatchid = csd.containerstepdispatchid AND csw.isuse = 0)
and cb.containercombinatename='{2}' and s1.stepinfoid = '{3}'";
        string strSql = string.Empty;
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            if (i != 0)
            {
                strSql += @"
                            UNION ALL
                            ";
            }
            DataRow item = dt.Rows[i];
            strSql += string.Format(sql, m_UserInfo.EmployeeID, m_UserInfo.FactoryID, item["containername"].ToString(), item["stepinfoid"].ToString(), item["notes"].ToString());
        }
        return DatabaseAccess.DBUtility.DatabaseHelper.Query_ReturnDatTable(strSql);
    }

    /// <summary>
    /// 验证是否批次接收
    /// </summary>
    /// <param name="containerID"></param>
    /// <returns></returns>
    private bool IsContainerReceive(string containerID)
    {
        string sql = string.Format("SELECT 1 FROM rbordercontainerreceive r WHERE r.containerid = '{0}' AND r.receivedate IS NOT NULL", containerID);
        if (DatabaseAccess.DBUtility.DatabaseHelper.GetSingle(sql) != null)
        {
            return true;
        }
        return false;
    }

    /// <summary>
    /// 初始化工步报工页面
    /// </summary>
    /// <param name="context"></param>
    public void InitData(HttpContext context)
    {
        DataSet ds = new DataSet();
        if (string.IsNullOrWhiteSpace(m_UserInfo.FactoryID))
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "登录信息失效，请重新登录" }));
            return;
        }
        string strSelectChecker = m_Common.GetFatoryAttributes(m_UserInfo.FactoryID, "报工选择检验"); //获取工厂报工是否选择检验员信息
        string strSelectChecker_ = m_Common.GetFatoryAttributes(m_UserInfo.FactoryID, "报工自检"); //获取工厂报工是否有自检信息
        if (strSelectChecker == "是")
        {
            string strRole = "";
            strRole = m_Common.GetEnterpriseAttributes("检验员角色");
            if (strRole == "")
            {
                strRole = "WorkReportTFW";
            }
            Dictionary<string, string> para = new Dictionary<string, string>();
            para.Add("RoleName", strRole);
            para.Add("FactoryID", m_UserInfo.FactoryID);
            DataTable dtChecker = m_Common.GetEmployeeRoles(para);
            DataRow dr = dtChecker.NewRow();
            dr["FULLNAME"] = "请选择";
            dr["CHECKERID"] = "";
            dtChecker.Rows.InsertAt(dr, 0);
            dtChecker.TableName = "dtChecker";
            ds.Tables.Add(dtChecker);
        }
        if (strSelectChecker_ == "是")
        {
            DataTable dtSelf = new DataTable();
            dtSelf.TableName = "dtSelf";
            ds.Tables.Add(dtSelf);
        }
        if (m_UserInfo.Factory.Contains("叶片"))
        {
            DataTable dtYePian = new DataTable();
            dtYePian.TableName = "dtYePian";
            ds.Tables.Add(dtYePian);
        }
        DataTable dtUom = m_Common.GetUom();
        dtUom.TableName = "dtUom";
        DataRow dru = dtUom.NewRow();
        dru["UOMNAME"] = "请选择";
        dru["UOMID"] = "";
        dtUom.Rows.InsertAt(dru, 0);
        ds.Tables.Add(dtUom);
        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = true, DBDataSet = ds }));
    }

    /// <summary>
    /// 获取工步列表数据（热表）
    /// </summary>
    /// <param name="context"></param>
    public void GetRBStepInfoList(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("ScanContainerName", context.Request["scanContainer"].ToString());
        if (string.IsNullOrWhiteSpace(para["ScanContainerName"]))
        {
            result.Result = false; result.Message = "请输入批次";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        para.Add("FactoryID", m_UserInfo.FactoryID);
        para.Add("WorkerID", m_UserInfo.EmployeeID.ToString());
        para.Add("CurrentPageIndex", context.Request["pageIndex"].ToString());
        para.Add("PageSize", context.Request["pageSize"].ToString());
        para["ScanContainerName"] = m_Common.ContainerScan(para["ScanContainerName"]);
        para["CurrentWorkflowStep"] = context.Request["currStep"].ToString();

        result = reportBusiness.GetRBStepInfoReportList(para);
        //加入判断是否有录入检测项
        result.DBTable.Columns.Add("IsFillCheckPoint");
        string msg = string.Empty;
        foreach (DataRow item in result.DBTable.Rows)
        {
            msg = "";
            m_ContainerObj.IsValidRBCheckPointByStepinfo(item, 0, ref msg);
            item["IsFillCheckPoint"] = msg;
            //验证批次是否可报
            msg = "";
            if (!m_DispatchObj.IsVaildSeqForStepInfo(item["CONTAINERID"].ToString(), item["workflowstepid"].ToString(), ref msg))
            {
                result.Result = false; result.Message = msg;
                break;
            }
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 获取工步列表数据（未启用）
    /// </summary>
    /// <param name="context"></param>
    public void GetStepInfoList(HttpContext context)
    {
        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("FactoryID", m_UserInfo.FactoryID);
        para.Add("WorkerID", m_UserInfo.EmployeeID.ToString());
        para.Add("CurrentPageIndex", context.Request["pageIndex"].ToString());
        para.Add("PageSize", context.Request["pageSize"].ToString());
        para.Add("ScanContainerName", context.Request["scanContainer"].ToString());
        if (!string.IsNullOrWhiteSpace(para["ScanContainerName"].ToString()))
        {
            para["ScanContainerName"] = m_Common.ContainerScan(para["ScanContainerName"].ToString());
        }
        para["CurrentWorkflowStep"] = context.Request["currStep"].ToString();
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        result = reportBusiness.GetStepInfoReportList(para);
        //加入判断是否有录入检测项
        result.DBTable.Columns.Add("IsFillCheckPoint");
        DataTable dt = result.DBTable.Copy();
        foreach (DataRow item in result.DBTable.Rows)
        {
            if (item["ContainerType"].ToString() == "7")
            {
                continue;
            }
            dt.Rows.Clear();
            dt.Rows.Add(item.ItemArray);
            var re = m_ContainerObj.JudgeContainerCheckPoint(dt);
            if (!re.Result)
            {
                item["IsFillCheckPoint"] = re.Message;
            }
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 获取结余件确认人
    /// </summary>
    /// <param name="context"></param>
    public void GetSurPlusEmployeeInfo(HttpContext context)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("txtScanSurPlusEmployeeName");
        dt.Columns.Add("lblSurPlusEmployeeID");
        string strCard = context.Request["scanSurPlusEmployeeID"].ToString();
        uMES_AjaxEmployeeDto dto = uMESBusinessFactory.instance.GetuMESLoginObject().GetEmployeeByCardNum(strCard);
        if (dto == null || string.IsNullOrWhiteSpace(dto.strEmployeeID))
        {
            dto = uMESBusinessFactory.instance.GetuMESLoginObject().GetEmployeeByEmployeename(strCard);
        }
        if (dto == null || string.IsNullOrWhiteSpace(dto.strEmployeeID))
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "扫描的卡号无效" }));
            return;
        }
        Dictionary<string, string> para = new Dictionary<string, string>();
        string strRoleworkcenter = m_Common.GetEnterpriseAttributes("工区长角色");
        if (!string.IsNullOrWhiteSpace(strRoleworkcenter))
        {
            para["FactoryID"] = m_UserInfo.FactoryID;
            para["RoleName"] = strRoleworkcenter;
            para["EmployeeID"] = dto.strEmployeeID;
            if (m_Common.GetEmployeeRoles(para).Rows.Count == 1)
            {
                DataRow dr = dt.NewRow();
                dr["txtScanSurPlusEmployeeName"] = dto.strFullName;
                dr["lblSurPlusEmployeeID"] = dto.strEmployeeID;
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, DBTable = dt }));
                return;
            }
        }
        string strRoleteam = m_Common.GetEnterpriseAttributes("班组长角色");
        if (!string.IsNullOrWhiteSpace(strRoleteam))
        {
            para["FactoryID"] = m_UserInfo.FactoryID;
            para["RoleName"] = strRoleteam;
            para["EmployeeID"] = dto.strEmployeeID;
            if (m_Common.GetEmployeeRoles(para).Rows.Count == 1)
            {
                DataRow dr = dt.NewRow();
                dr["txtScanSurPlusEmployeeName"] = dto.strFullName;
                dr["lblSurPlusEmployeeID"] = dto.strEmployeeID;
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, DBTable = dt }));
                return;
            }
        }
    }

    /// <summary>
    /// 获取填充数据
    /// </summary>
    /// <param name="context"></param>
    public void GetFillData(HttpContext context)
    {
        DataSet ds = new DataSet();
        DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request["params"].ToString());
        if (dt.Rows[0]["ContainerType"].ToString() == "3")
        {
            //获取子批次
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("ContainerId", dt.Rows[0]["ContainerId"].ToString());
            dic.Add("WorkflowStepId", dt.Rows[0]["WorkflowstepId"].ToString());
            dic.Add("StepInfoId", dt.Rows[0]["StepInfoId"].ToString());
            DataTable newdt = reportBusiness.GetContainerStepInfoNoReportChildList(dic);
            newdt.TableName = "dtChild";
            ds.Tables.Add(newdt);
        }
        else if (dt.Rows[0]["ContainerType"].ToString() == "7")
        {
            dt.Columns.Add("WorkerID");
            dt.Rows[0]["WorkerID"] = m_UserInfo.EmployeeID.ToString();
            DataTable dtSingle = reportBusiness.GetSingleContainerStepInfoReportList(dt.Rows[0]);
            //加入判断是否有录入检测项
            dtSingle.Columns.Add("IsFillCheckPoint");
            DataTable dt1 = dtSingle.Copy();
            foreach (DataRow item in dtSingle.Rows)
            {
                dt1.Rows.Clear();
                dt1.Rows.Add(item.ItemArray);
                var re = m_ContainerObj.JudgeContainerCheckPoint(dt1);
                if (!re.Result)
                {
                    item["IsFillCheckPoint"] = "未录入";
                }
            }
            dtSingle.TableName = "dtSingle";
            ds.Tables.Add(dtSingle);
        }
        //获取工序设备信息 
        DataTable dtResource = ypBusiness.GetContainerCurrentSpecResource(dt.Rows[0]["ContainerID"].ToString(), dt.Rows[0]["WorkflowStepId"].ToString());
        dtResource.TableName = "dtResource";
        ds.Tables.Add(dtResource);
        //集件信息
        if (!string.IsNullOrWhiteSpace(dt.Rows[0]["BomID"].ToString()))
        {
            Dictionary<string, string> newpara = new Dictionary<string, string>();
            newpara.Add("BomID", dt.Rows[0]["BomID"].ToString());
            newpara.Add("ContainerID", dt.Rows[0]["ContainerID"].ToString());
            newpara.Add("WorkFlowID", dt.Rows[0]["WorkFlowID"].ToString());
            newpara.Add("Sequence", dt.Rows[0]["Sequence"].ToString());
            newpara.Add("IsCurrentStep", "1");
            DataTable dtCollect = m_issueData.GetCollectPieceManageBOMList(newpara);
            dtCollect.TableName = "dtCollect";
            ds.Tables.Add(dtCollect);
        }
        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = true, DBDataSet = ds }));
    }
    /// <summary>
    /// 设置实测值录入
    /// </summary>
    /// <param name="context"></param>
    public void SetInputCheckPoint(HttpContext context)
    {
        DataTable dtMain = JsonConvert.DeserializeObject<DataTable>(context.Request["mainDt"].ToString());//选中的工步
        if (dtMain.Rows[0]["ContainerType"].ToString() != "7" && dtMain.Rows.Count > 1)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "只能选择一条数据进行实测值录入" }));
            return;
        }
        if (string.IsNullOrWhiteSpace(dtMain.Rows[0]["ContainerID"].ToString())) //如果批次ID为空，则表示是合卡批次
        {
            string sql = @"SELECT csd.containerstepdispatchid,c.containername,c.containerid,ws.workflowstepname,csd.workflowstepid,c.workflowid,c.productid,
            s1.stepinfoid,s1.stepno,s1.stepseq,s1.description stepinfoname,csd.createdate,c.qty wipqty,csd.qty disqty,c.containertype,
            DECODE(c.CONTAINERTYPE,2,'批量加工',3,'批量带子序号', 7,'单件加工') AS CONTAINERTYPENAME
            FROM containercombinate cb 
            LEFT JOIN containercurrentinfo c ON c.containerid = cb.containerid
            LEFT JOIN containerstepdispatch2 csd ON csd.containerid = cb.containerid
            LEFT JOIN Workflowstep ws ON ws.workflowstepid = csd.workflowstepid
            LEFT JOIN stepinfo s1 ON s1.stepinfoid = csd.stepinfoid
            WHERE cb.containercombinatename = '{0}' AND csd.workflowstepid = '{1}' AND csd.stepinfoid = '{2}' AND csd.isuse = 0 AND c.containerstatus=1 
            AND NOT EXISTS(SELECT 1 FROM containerstepworkreport2 csw WHERE csw.containerstepdispatchid = csd.containerstepdispatchid AND csw.isuse = 0)";
            dtMain = DatabaseAccess.DBUtility.DatabaseHelper.Query_ReturnDatTable(string.Format(sql, dtMain.Rows[0]["ContainerName"].ToString(), dtMain.Rows[0]["workflowstepid"].ToString(), dtMain.Rows[0]["stepinfoid"].ToString()));
        }

        bool isValid = true;
        string msg = "";
        foreach (DataRow item in dtMain.Rows)
        {
            if (m_Common.JudeContainerHold(item["ContainerId"].ToString(), ref msg))
            {
                msg = "该批次已暂停，暂停原因：" + msg;
                isValid = false;
                break;
            }
        }
        if (isValid)
        {
            context.Session["PopupData"] = dtMain;
        }
        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = isValid, Message = msg }));
    }

    /// <summary>
    /// 保存工步报工数据
    /// </summary>
    /// <param name="context"></param>
    public void SaveStepInfoWorkReportData(HttpContext context)
    {
        DataTable dtMain = JsonConvert.DeserializeObject<DataTable>(context.Request["mainDt"].ToString());//选中的工步
        DataTable dtFill = JsonConvert.DeserializeObject<DataTable>(context.Request["fillDt"].ToString());//填写的数据
        DataTable dtChild = JsonConvert.DeserializeObject<DataTable>(context.Request["childDt"].ToString());//批量子序号
        if (dtMain.Rows.Count == 0 || dtFill.Rows.Count == 0)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "数据过期，请刷新" }));
            return;
        }
        //
        DataRow drFill = dtFill.Rows[0];//填写数据
        string msg = "";
        string containerType = dtMain.Rows[0]["ContainerType"].ToString();
        string ContainerStepDispatchInfoIDs = "";
        //string containerIDs_str = "";
        if (m_Common.JudeContainerHold(dtMain.Rows[0]["ContainerId"].ToString(), ref msg))
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "该批次已暂停，暂停原因：" + msg }));
            return;
        }
        if (!IsContainerReceive(dtMain.Rows[0]["ContainerId"].ToString()))
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "批次未接受，无法报工" }));
            return;
        }
        int count = reportBusiness.GetContainerCurrentIsReportType_3(dtMain.Rows[0]["ContainerId"].ToString(), dtMain.Rows[0]["WorkflowstepId"].ToString());
        if (count > 0 && dtMain.Rows[0]["stepchecknum"].ToString() == "1")
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "该序存在测试检验" }));
            return;
        }
        if (containerType == "3")
        {
            if (!string.IsNullOrWhiteSpace(drFill["iNMTQty"].ToString()))
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "批量带子序号的批次不允许进行试件报工操作" }));
                return;
            }
            if (dtChild.Rows.Count == 0)
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "未选择批量子序号" }));
                return;
            }
            if (!dtChild.Columns.Contains("SelfCheckLossQty"))
            {
                dtChild.Columns.Add("SelfCheckLossQty");
            }
        }
        bool isValid = true;
        foreach (DataRow dr in dtMain.Rows)
        {
            msg = "";
            if (!m_ContainerObj.IsValidRBCheckPointByStepinfo(dr, 0, ref msg))
            {
                isValid = false; msg = "未录入实测值";
                break;
            }
            if (m_ContainerObj.IsCombinateContainer(dr["ContainerId"].ToString()))
            {
                isValid = false; msg = string.Format("批次：{0}已合卡", dr["ContainerName"].ToString());
                break;
            }
            ContainerStepDispatchInfoIDs += " OR csd.containerstepdispatchid='" + dr["ContainerStepDispatchID"] + "'";
            //containerIDs_str += "'" + dr["ContainerID"].ToString() + "',";
        }
        if (!isValid)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "未录入实测值" }));
            return;
        }
        if (string.IsNullOrWhiteSpace(ContainerStepDispatchInfoIDs))
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "未在页面记录找到报工对应的派工记录" }));
            return;
        }
        ContainerStepDispatchInfoIDs = ContainerStepDispatchInfoIDs.Substring(3);
        //containerIDs_str = containerIDs_str.Trim(',');
        //containerIDs_str = containerIDs_str.Trim('\'');
        DataTable dt_ = GetWorkReportTimeReallyDisReportNum(ContainerStepDispatchInfoIDs);
        if (dt_.Rows.Count == 0)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "未在页面记录找到报工对应的派工记录" }));
            return;
        }
        if (!reportBusiness.IsVaildDispatchForStepInfoWorkReport(ContainerStepDispatchInfoIDs))
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "派工记录已撤销，请刷新页面" }));
            return;
        }
        int oldreportqty = int.Parse(dtMain.Rows[0]["disworkqty"].ToString());
        foreach (DataRow dr_ in dt_.Rows)
        {
            if (int.Parse(dr_["reportqty"].ToString()) != oldreportqty)
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "勾选的派工记录对应的报工记录数据已更新，请重新查询数据再进行报工" }));
                return;
            }
        }
        string strSelectChecker_ = m_Common.GetFatoryAttributes(m_UserInfo.FactoryID, "报工自检"); //获取工厂报工是否有自检信息
        if (strSelectChecker_ != "是" && string.IsNullOrWhiteSpace(drFill["reportQty"].ToString()))
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "未填写报工数" }));
            return;
        }
        int type = int.Parse(drFill["checkType"].ToString());
        ContainerStepWorkReportDTO dto = new ContainerStepWorkReportDTO();
        dto.WorkerID = m_UserInfo.EmployeeID.ToString();
        dto.FactoryID = m_UserInfo.FactoryID;
        dto.WorkCenterID = m_UserInfo.WorkCenterID;
        dto.TeamID = m_UserInfo.TeamID;
        dto.FirstContainerNo = ""; //首件批次号
        dto.KeyProcessBatchNo = ""; //关键过程批次号
        dto.Note = drFill["notes"].ToString(); //备注 
        if (!string.IsNullOrWhiteSpace(drFill["iNMTQty"].ToString()))
        {
            dto.Specimenqty = int.Parse(drFill["iNMTQty"].ToString());//试件数
            if (!string.IsNullOrWhiteSpace(drFill["iNMTLossQty"].ToString()))
            {
                dto.Specimenlossqty = int.Parse(drFill["iNMTLossQty"].ToString());//试件废票数
            }
            type = 3;
        }
        string contianerstepworkreportid = "";
        List<object[]> SQLStringList = new List<object[]>();
        uMESProcessResult result = new uMESProcessResult() { Result = true, Message = "报工成功" };
        foreach (DataRow item in dtMain.Rows)
        {
            if (IsOtherCheckPointed(item["ContainerID"].ToString(), item["StepInfoID"].ToString(), item["WorkflowStepID"].ToString()))
            {
                result.Result = false;
                result.Message = "存在其他工人录入检测项但未报工，请等待别人报工完成，或删除别人录入但未报工的检测项";
                break;
            }
            //验证特殊过程工序
            if (rbBusiness.IsErrorSpecialCourseSpecReport(item["ContainerID"].ToString(), item["ContainerStepDispatchID"].ToString(), m_UserInfo.EmployeeName, ref msg))
            {
                result.Result = false;
                result.Message = msg;
                break;
            }
            dto.ContainerID = item["ContainerID"].ToString();
            dto.WorkflowstepID = item["WorkflowStepID"].ToString();
            dto.StepInfoID = item["StepInfoID"].ToString();
            dto.ResourceID = string.IsNullOrWhiteSpace(drFill["resourceId"].ToString()) ? "" : drFill["resourceId"].ToString();
            dto.CheckerID = string.IsNullOrWhiteSpace(drFill["checkerId"].ToString()) ? "" : drFill["checkerId"].ToString();
            dto.SelfCheckOutofToleranceQty = string.IsNullOrWhiteSpace(drFill["selfCheckOutofToleranceQty"].ToString()) ? 0 : int.Parse(drFill["selfCheckOutofToleranceQty"].ToString());
            dto.SelfCheckLossQty = string.IsNullOrWhiteSpace(drFill["selfCheckLossQty"].ToString()) ? 0 : int.Parse(drFill["selfCheckLossQty"].ToString());
            if (containerType == "7")
            {
                dto.Qty = 1;//报工数
                dto.SeleCheckQualifiedQty = 0;//自检合格
            }
            else
            {
                if (strSelectChecker_ == "是") //如果是报工自检
                {
                    dto.SeleCheckQualifiedQty = string.IsNullOrWhiteSpace(drFill["reportQty"].ToString()) ? 0 : int.Parse(drFill["reportQty"].ToString());//自检合格数
                    dto.Qty = dto.SeleCheckQualifiedQty + dto.SelfCheckOutofToleranceQty + dto.SelfCheckLossQty; //则报工数为三者之和
                }
                else
                {
                    dto.Qty = int.Parse(drFill["reportQty"].ToString());//报工数
                    dto.SeleCheckQualifiedQty = 0;//自检合格数
                }
            }
            if (!string.IsNullOrWhiteSpace(drFill["lblSurPlusEmployeeID"].ToString()))//结余件确认人
            {
                dto.SurplusEmployeeID = drFill["lblSurPlusEmployeeID"].ToString();
            }
            if (!string.IsNullOrWhiteSpace(drFill["commentsFirst"].ToString()) && !string.IsNullOrWhiteSpace(drFill["uOMField"].ToString()))
            {
                dto.UOM2ID = drFill["uOMField"].ToString();
                dto.Qty2 = int.Parse(drFill["commentsFirst"].ToString());
            }
            dto.CheckType = type;
            dto.ContainerStepDispatchID = item["ContainerStepDispatchID"].ToString();
            contianerstepworkreportid = Guid.NewGuid().ToString();
            dto.ContainerStepWorkReportID = contianerstepworkreportid;
            SQLStringList.Add(reportBusiness.FillContainerStepInfoWorkReportDataTrans(dto, ""));//插入报工数据
            Dictionary<string, string> para = new Dictionary<string, string>();
            para.Add("type", "2");
            para.Add("WorkerID", dto.WorkerID);
            para.Add("ContainerStepDispatchID", item["ContainerStepDispatchID"].ToString());
            SQLStringList.Add(reportBusiness.FillReceviceDispatch2(para));//更新派工表接收数据
            SQLStringList.Add(reportBusiness.UpdateStepInfoCheckPointReport(dto));//更新可能的检测项
        }
        if (!result.Result)
        {
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        //插入子序号到明细表
        foreach (DataRow row in dtChild.Rows)
        {
            ContainerStepWorkReportChildDTO entity = new ContainerStepWorkReportChildDTO();
            entity.ChildContainerID = row["ContainerID"].ToString();
            entity.SelfCheckLossQty = string.IsNullOrWhiteSpace(row["SelfCheckLossQty"].ToString()) ? "0" : row["SelfCheckLossQty"].ToString();
            entity.ContainerStepWorkReportID = contianerstepworkreportid;
            SQLStringList.Add(reportBusiness.FillContainerStepInfoWorkReportChild2(entity));
        }
        //SQLStringList.Add(reportBusiness.FillUpdateStepCheckNum(containerIDs_str, dto.CheckType == 1 ? 1 : 2));
        if (SQLStringList.Count > 0)
        {
            if (!DatabaseAccess.DBUtility.DatabaseHelper.ExecuteSqlTran(SQLStringList))
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "报工异常" }));
                return;
            }
        }
        //m_DispatchObj.UpdateDispatchIsCompleteStatus(ContainerStepDispatchInfoIDs.Replace("csd", "csw")); //更新派工记录是否完工状态
        DataTable dt1 = dtMain.DefaultView.ToTable(true, new string[4] { "ContainerID", "WorkflowStepID", "WipQty", "StepInfoRev" });
        FillStepWorkReportInfo(dt1);//更新工序到报工表
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 验证是否其他工人录入过检验值
    /// </summary>
    /// <param name="containerID"></param>
    /// <param name="stepInfoID"></param>
    /// <param name="workflowstepID"></param>
    /// <returns></returns>
    private bool IsOtherCheckPointed(string containerID, string stepInfoID, string workflowstepID)
    {
        //验证是否有其他工人录入检测项，但是没报工的
        string strSql = @"SELECT 1 FROM  stepcheckpointresult sp
LEFT JOIN stepcheckpoint s ON s.stepcheckpointid = sp.stepcheckpointid
WHERE sp.containerid = '{0}' AND s.stepinfoid = '{1}' AND s.workflowstepid = '{2}' AND sp.containerstepworkreportid IS NULL
and sp.workerid <> '{3}'";
        strSql = string.Format(strSql, containerID, stepInfoID, workflowstepID, m_UserInfo.EmployeeID.ToString());
        if (DatabaseAccess.DBUtility.DatabaseHelper.GetSingle(strSql) != null)
        {
            return true;
        }
        return false;
    }

    /// <summary>
    /// 判断工步报工数据是否过时
    /// </summary>
    /// <param name="containerStepDispatchInfoIDs"></param>
    /// <returns></returns>
    private DataTable GetWorkReportTimeReallyDisReportNum(string containerStepDispatchInfoIDs)
    {
        string strSql = @"SELECT csd.containerstepdispatchid,csd.qty,sum(nvl(cw.qty,0)) reportqty FROM containerstepdispatch2 csd
LEFT JOIN containerstepworkreport2 cw on csd.containerstepdispatchid = cw.containerstepdispatchid AND cw.isuse=0
WHERE  1=1";
        strSql += string.Format(" and ({0})", containerStepDispatchInfoIDs);
        strSql += " and csd.isuse=0 ";
        strSql += " GROUP BY csd.qty,csd.containerstepdispatchid ";
        return DatabaseAccess.DBUtility.DatabaseHelper.Query_ReturnDatTable(strSql);
    }

    /// <summary>
    /// 填充工序报工
    /// </summary>
    /// <param name="dtMain"></param>
    /// <param name="dto"></param>
    /// <returns></returns>
    private void FillStepWorkReportInfo(DataTable dtMain)
    {
        List<object[]> SQLStringList = new List<object[]>();
        foreach (DataRow item in dtMain.Rows)
        {
            if (IsExistStepReportInfo(item)) //如果存在工序报工，则跳过，避免重复报工
            {
                continue;
            }
            string strSql = @"SELECT SUM(NVL(csw.qty,0)) reportqty,max(csw.qty) maxqty FROM stepinfo s 
                            LEFT JOIN containerstepworkreport2 csw ON csw.stepinfoid = s.stepinfoid AND csw.containerid = '{0}' AND csw.workflowstepid = '{1}' AND csw.isuse = 0
                            WHERE s.workflowstepid = '{1}' AND s.revision = '{2}'
                            GROUP BY s.stepinfoid";
            strSql = string.Format(strSql, item["ContainerID"].ToString(), item["WorkflowStepID"].ToString(), item["StepInfoRev"].ToString());
            DataTable dt = DatabaseAccess.DBUtility.DatabaseHelper.Query_ReturnDatTable(strSql);
            DataRow[] drs = dt.Select("reportqty<" + int.Parse(item["WipQty"].ToString()) + "");
            if (drs.Length > 0) //如果存在报工未完成的工步，则不添加工序报工
            {
                continue;
            }
            strSql = "SELECT cw.containerstepdispatchid FROM containerstepdispatch cw WHERE cw.containerid = '{0}' AND cw.workflowstepid = '{1}' AND cw.isuse = 0";
            strSql = string.Format(strSql, item["ContainerID"].ToString(), item["WorkflowStepID"].ToString());
            DataTable dt1 = DatabaseAccess.DBUtility.DatabaseHelper.Query_ReturnDatTable(strSql);
            ContainerStepWorkReportDTO dto = new ContainerStepWorkReportDTO();
            dto.ContainerID = item["ContainerID"].ToString();
            dto.WorkflowstepID = item["WorkflowStepID"].ToString();
            dto.Qty = int.Parse(dt.Rows[0]["maxqty"].ToString());
            dto.WorkerID = m_UserInfo.EmployeeID.ToString();
            dto.FactoryID = m_UserInfo.FactoryID;
            dto.WorkCenterID = m_UserInfo.WorkCenterID;
            dto.ResourceID = "";
            dto.CheckerID = "";
            dto.FirstContainerNo = ""; //首件批次号
            dto.KeyProcessBatchNo = ""; //关键过程批次号
            dto.TeamID = m_UserInfo.TeamID;
            //dto.SeleCheckQualifiedQty = int.Parse(dt.Compute("SUM(selfcheckqualifiedqty)", string.Empty).ToString());
            //dto.SelfCheckOutofToleranceQty = int.Parse(dt.Compute("SUM(selfcheckoutoftoleranceqty)", string.Empty).ToString());
            //dto.SelfCheckLossQty = int.Parse(dt.Compute("SUM(selfchecklossqty)", string.Empty).ToString());
            dto.CheckType = 2;
            dto.ContainerStepDispatchID = dt1.Rows.Count > 0 ? dt1.Rows[0]["containerstepdispatchid"].ToString() : "";
            dto.ContainerStepWorkReportID = Guid.NewGuid().ToString();
            SQLStringList.Add(reportBusiness.FillContainerStepWorkReportInfoTrans(dto, ""));
            //SQLStringList.Add(reportBusiness.FillUpdateStepCheckNum(item["ContainerID"].ToString(), 2));//更新批次检验类型
        }
        if (SQLStringList.Count > 0)
        {
            DatabaseAccess.DBUtility.DatabaseHelper.ExecuteSqlTran(SQLStringList);
        }
    }

    /// <summary>
    /// 是否存在工序报工
    /// </summary>
    /// <param name="dr"></param>
    /// <returns></returns>
    public bool IsExistStepReportInfo(DataRow dr)
    {
        string sql = "SELECT 1 FROM containerstepworkreport csw WHERE csw.containerid = '{0}' AND csw.workflowstepid = '{1}' AND csw.isuse = 0";
        sql = string.Format(sql, dr["ContainerID"].ToString(), dr["WorkflowstepID"].ToString());
        if (DatabaseAccess.DBUtility.DatabaseHelper.Query_ReturnDatTable(sql).Rows.Count == 0)
        {
            return false;
        }
        return true;
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}